/*
 * Copyright 2012-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.s666.demo.controller;

import java.util.Collections;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.s666.demo.common.response.Result;
import com.s666.demo.common.response.ResultVO;
import com.s666.demo.exception.MessageRender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 错误处理页面, 用于处理404
 * @author lijin
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class DefaultErrorController extends AbstractErrorController {

    @Autowired
    protected MessageRender messageRender;

    public DefaultErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes, Collections.emptyList());
    }
    @Override
    public String getErrorPath() {
        return "/";
    }
    /**
     * html
     * @param request
     * @param response
     * @return
     */
    @RequestMapping( produces = "text/html")
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        Map<String, Object> body = Collections.unmodifiableMap(getErrorAttributes(
               request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        HttpStatus status = getStatus(request);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error/404.html");
        modelAndView.addObject("rsp_code", status.value());
        modelAndView.addObject("rsp_msg", status.getReasonPhrase());
        modelAndView.addObject("rsp_data",  body.get("trace"));
        return modelAndView;
    }
    /**
     * json
     * @param request
     * @return
     */
    @RequestMapping( produces = "application/json")
    @ResponseBody
    public ResultVO errorJson(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.TEXT_HTML));
        HttpStatus status = getStatus(request);

        return Result.fail(status.value() + "", status.getReasonPhrase(), (String) body.get("trace"));
    }

    /**
     * 通用
     * @param request
     * @param response
     * @return
     */
    @RequestMapping
    public ModelAndView error(HttpServletRequest request,
                              HttpServletResponse response) {
        return errorHtml(request,response);
    }

    @Value("${spring.profiles.active}")
    private String env;
    /**
     * 是否打印跟踪结果
     * @param request
     * @param produces
     * @return
     */
    private boolean isIncludeStackTrace(HttpServletRequest request,
                                        MediaType produces) {
        String cmp = "prod";
        if( cmp.equals(env) ){
            return false;
        }else{
            boolean result =getTraceParameter(request);
            return result;
        }
    }
}
